<template>
    <ui-navbar class="bi-isolation-select" type="custom" :data="isolationTypes">
        <template slot="item" slot-scope="{ item, isFirst, isLast }">
            <div class="bi-isolation-select__item" :class="{'is-first': isFirst, 'is-last': isLast, 'is-active': activeTypeMap[item.value]}" @click="handleItemClick(item)">
                <bi-isolation-type :type="item.value" :active="activeTypeMap[item.value]">
                    {{item.text}}
                </bi-isolation-type>
            </div>
        </template>
    </ui-navbar>
</template>
<script>
import UiNavbar from 'board/components/navbar'
import { loadIsolationTypes } from 'board/apis/isolation'
import BiIsolationType from 'board/common/isolation-type'

export default {
    name: 'BiIsolationSelect',
    components: {
        UiNavbar,
        BiIsolationType
    },
    props: {
        value: {
            type: Array,
            default: () => []
        },
        multiple: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            activeType: this.value,
            isolationTypes: []
        }
    },
    computed: {
        activeTypeMap () {
            return this.activeType.reduce((rs, v) => {
               rs[v] = true
               return rs
            }, {})
        }
    },
    watch: {
        value () {
            this.activeType = this.value
        }
    },
    created () {
        this.loadIsolationTypes()
    },
    methods: {
        handleItemClick (item) {
            if (this.activeTypeMap[item.value]) {
                this.activeType = this.activeType.filter(v => v !== item.value)
            } else {
                if (this.multiple) {
                    this.activeType.push(item.value)
                } else {
                    this.activeType = [item.value]
                }
            }
            this.$emit('input', this.activeType)
            this.$emit('change', {
                value: this.activeType
            })
        },
        loadIsolationTypes () {
            return loadIsolationTypes().then(rs => {
                this.isolationTypes = rs
            })
        }
    }
}
</script>
<style lang="scss">
.bi-isolation-select__item{
    padding-left: 5px;
    padding-right: 5px;
    &.is-first{
        padding-left: 0;
    }
    &.is-last{
        padding-right: 0;
    }
}
</style>